import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import { Toaster } from '@/components/ui/toaster'
import { addFeedback } from '@/apis/feedback'
import { useToast } from '@/hooks/use-toast'

export function Feedback() {
  const [content, setContent] = useState('')
  const [contactInfo, setContactInfo] = useState('')
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const { toast } = useToast()
  const handleSubmit = async () => {
    await addFeedback({ data: { content, contact_info: contactInfo } })
    // 清空输入框
    setContent('')
    setContactInfo('')
    // 关闭弹窗
    setIsDialogOpen(false)
    // 提示完成
    toast({
      title: '提交成功',
      description: '感谢您的反馈！'
    })
  }

  return (
    <>
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogTrigger asChild>
          <Button variant="ghost" onClick={() => setIsDialogOpen(true)}>
            建议反馈
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>建议反馈</DialogTitle>
            <DialogDescription>请在下方输入您的建议或反馈。</DialogDescription>
          </DialogHeader>
          <div className="grid gap-4">
            <Textarea
              rows={3}
              placeholder="请输入您的建议或反馈..."
              value={content}
              onChange={(e) => setContent(e.target.value)}
            />
            <Input
              type="text"
              placeholder="请输入您的联系方式..."
              value={contactInfo}
              onChange={(e) => setContactInfo(e.target.value)}
            />
            <Button
              type="submit"
              size="sm"
              className="px-3"
              onClick={handleSubmit}
            >
              提交
            </Button>
          </div>
          <DialogFooter className="sm:justify-start">
            <DialogClose asChild>
              <Button type="button" variant="secondary">
                关闭
              </Button>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Toaster />
    </>
  )
}
